package com.authenticateCenter.assembler;

import com.authenticateCenter.domain.entity.Authority;
import com.authenticateCenter.domain.entity.Role;
import com.authenticateCenter.domain.vo.RoleVo;

import java.util.List;
import java.util.stream.Collectors;

import com.authenticateCenter.service.IAuthorityService;
import com.authenticateCenter.service.IRoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.common.mybaits.CustomPage;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import static com.authenticateCenter.factory.AuthorityFactory.AUTHORITY_CONVERT;
import static com.authenticateCenter.factory.RoleFactory.ROLE_CONVERT;


/**
 * @author 大忽悠
 */
@Component
@RequiredArgsConstructor
public class RoleAssembler implements InfoAssembler<RoleVo, Integer, Integer> {
    private final IRoleService iRoleService;
    private final IAuthorityService iAuthorityService;

    @Override
    public RoleVo assembler(Integer uid) {
        return null;
    }

    @Override
    public List<RoleVo> assemblers(CustomPage customPage, Integer uid) {
        List<Role> roles = getRoles(customPage, uid);
        if (roles == null || roles.isEmpty()) {
            return null;
        }
        //过滤掉被禁用的角色
        List<RoleVo> roleVos = roles.stream().filter(role -> role.getEnabled() == 1)
                .map(role -> ROLE_CONVERT.toRoleVo(role))
                .collect(Collectors.toList());
        //过滤掉被禁用的权限
        roleVos.forEach(roleVo ->
                roleVo.setAuthorityList(iAuthorityService.getAuthoritysByRid(roleVo.getId(), null).stream()
                        .filter(Authority::enableIf)
                        .map(authority -> AUTHORITY_CONVERT.toAuthorityVo(authority))
                        .collect(Collectors.toList())));
        return roleVos;
    }

    private List<Role> getRoles(CustomPage customPage, Integer uid) {
        if (uid == null) {
            return getRolesByPage(customPage, null);
        }
        return iRoleService.getRolesByUid(customPage, uid);
    }

    /**
     * @param customPage   分页信息
     * @param queryWrapper 查询条件
     * @return 角色列表
     */
    private List<Role> getRolesByPage(CustomPage customPage, QueryWrapper<Role> queryWrapper) {
        return CustomPage.getResult(customPage, new Role(), iRoleService, queryWrapper);
    }
}
